﻿#include "tcpclient.h"

#include <QDataStream>
#include <QEventLoop>

#if defined(_MSC_VER) && (_MSC_VER >= 1600)
#pragma execution_character_set("utf-8")
#endif
TcpClient::TcpClient(QObject *parent) : QObject(parent) {
  connectAllUsedSlots();
}

TcpClient::~TcpClient() { Disconnect(); }

void TcpClient::connectToServer(QString strIP, int nport) {
  if (socket.isOpen()) {
    if (socket.state() == QAbstractSocket::ConnectedState) {

      // 正常连接
      QString strData = "TCP连已连接:" + strIP + ":" + QString::number(nport);
      transMessage(strData);
      return;
    } else {
      // socket 连接失败后
      socket.close();
    }
  }

  socket.connectToHost(strIP, nport);
  socket.waitForConnected(); // 默认等待是3000ms
  if (socket.state() == QAbstractSocket::ConnectedState) {
    QString strMsg = "连接服务端成功:" + strIP + ":" + QString::number(nport);
    transMessage(strMsg);
  } else {
    transMessage("连接服务端失败");
    // 连接失败后对连接状态进行清理
    socket.close();
  }
}

void TcpClient::transMessage(const QString &msg) {
  qDebug() << msg << endl;
  emit TcpMsg(msg);
}
void TcpClient::sendData(const QString &data) {
  if (socket.isValid() && socket.state() == QAbstractSocket::ConnectedState) {
    socket.write(data.toUtf8());
    socket.flush();
    QString strData = "Data send to server:" + data;
    transMessage("发送数据:" + data);
  } else {
    transMessage("请先连接服务端。");
  }
}

void TcpClient::sendData(const QByteArray &data) {
  if (socket.isValid() && socket.state() == QAbstractSocket::ConnectedState) {
    socket.write(data);
    socket.flush();
    QString strData = "Data send to server:" + data;
    transMessage("发送数据:" + data);
  } else {
    transMessage("请先连接服务端。");
  }
}

void TcpClient::sendData(const char *data, int nlen) {
  if (socket.isValid() && socket.state() == QAbstractSocket::ConnectedState) {
    socket.write(data, nlen);
    socket.flush();
    QString strData = "Data send to server:";
    emit TcpMsg("发送数据：" + QString(data));
  } else {
    transMessage("请先连接服务端。");
  }
}

void TcpClient::dataReceived() {
  //  QDataStream in(&socket);
  //  int typeMsg;
  //  in >> typeMsg;

  auto readData = socket.readAll();
  transMessage("接收数据:" + readData);
  // 接受数据槽函数
}

void TcpClient::Disconnect() {
  socket.close();
  QString strData = ("断开连接");
  emit transMessage(strData);
}

QAbstractSocket::SocketState TcpClient::state() { return socket.state(); }

bool TcpClient::isValid() { return socket.isValid(); }

void TcpClient::connectAllUsedSlots() {
  connect(&socket, &QTcpSocket::connected, this,
          [&]() { transMessage("连接服务端完成"); });
  connect(&socket, &QTcpSocket::disconnected, this,
          [&]() { transMessage("从服务端断开"); });
  connect(&socket,
          QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this,
          [&](QAbstractSocket::SocketError socketError) {
            emit errorOccurred(socketError);
          });

  connect(&socket, &QTcpSocket::readyRead, this, &TcpClient::dataReceived);
}
